//app.js
const {
  $Toast
} = require('utils/iview/base/index');
const $util = require('utils/util');
const barTitle = require('./utils/bar-title');
const $api = require('./config/api');

App({
  onLaunch: function () {
    //周期性设置导航栏标题
    setInterval(function () {
      let temp = Math.round(Math.random() * (barTitle.list.length - 1));
      wx.setNavigationBarTitle({
        title: barTitle.list[temp]
      })
    }, 5 * 1000);
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  $Toast,
  $util,
  $api,
  globalData: {
    userInfo: null
  },
  ajax: function (options) {
    var url = 'https://route.showapi.com/255-1';
    return new Promise(function (resolve, reject) {
      wx.request({
        url: url,
        data: {
          showapi_appid: 36610,
          showapi_sign: 'f05f78810a8443fb8e007a267523e30c',
          ...options.data
        },
        success: res => {
          var data;
          if (res.statusCode == 200 && res.data.showapi_res_code == 0) {
            data = res.data.showapi_res_body;
            if (data.ret_code != 0) {
              $Toast({
                content: res.remark,
                type: 'error'
              });
            }
          } else {
            data = res.data;
          }
          resolve(data)
        }
      })
    })
  }
})